package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.pojo.PageResult;
import cn.itcast.hotel.pojo.RequestParams;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {

    @Autowired
    private RestHighLevelClient client;

    @Override
    public PageResult search(RequestParams params) {
        try {
            //1.准备Request
            SearchRequest searchRequest = new SearchRequest("hotel");
            //2.准备DSL
            //2.1 query

            BoolQueryBuilder boolQueryBuilder = getBoolQueryBuilder(params);

            //算分控制
            FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(/*原始查询*/boolQueryBuilder,/*算分函数*/new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{/*算分函数规则数组*/
                    new FunctionScoreQueryBuilder.FilterFunctionBuilder(/*一条算分函数规则*/
                            QueryBuilders.termQuery("isAD", true)/*过滤器条件*/,
                            ScoreFunctionBuilders.weightFactorFunction(10)/*算分函数*/
                            /*默认加权模式是multiply*/
                    )
            });

            searchRequest.source().query(functionScoreQueryBuilder);

            //2.2 paging
            Integer pageNum = params.getPage();
            Integer pageSize = params.getSize();
            searchRequest.source().from((pageNum - 1) * pageSize).size(pageSize);

            //2.3 sort
            String location = params.getLocation();
            if (location != null && !"".equals(location)) {
                searchRequest.source().sort(
                        SortBuilders
                                .geoDistanceSort("location", new GeoPoint(location/*"31.21, 121.5"*/))
                                .order(SortOrder.ASC)
                                .unit(DistanceUnit.KILOMETERS)
                );
            }

            //3.发送请求
            SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

            //4.解析响应json字符串
            return handleResponse(searchResponse);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private BoolQueryBuilder getBoolQueryBuilder(RequestParams params) {
        //构建BoolQuery
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //关键字搜索
        String key = params.getKey();
        if (key == null || "".equals(key)) {//健壮性判断,考虑前端传空值的情况
            boolQueryBuilder.must(QueryBuilders.matchAllQuery());
        } else {
            boolQueryBuilder.must(QueryBuilders.matchQuery("all", key));
        }
        //条件过滤
        //城市条件
        if (params.getCity() != null && !"".equals(params.getCity())) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("city", params.getCity()));
        }
        //品牌条件
        if (params.getBrand() != null && !"".equals(params.getBrand())) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("brand", params.getBrand()));
        }
        //星级条件
        if (params.getStarName() != null && !"".equals(params.getStarName())) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("starName", params.getStarName()));
        }
        //价格条件
        if (params.getMinPrice() != null && params.getMaxPrice() != null) {
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(params.getMinPrice()).lte(params.getMaxPrice()));
        }
        return boolQueryBuilder;
    }

    private PageResult handleResponse(SearchResponse searchResponse) {
        //4.解析响应json字符串
        SearchHits searchHits = searchResponse.getHits();//包含total,max_score,hits数组
        //4.1获取总条数
        long total = searchHits.getTotalHits().value;//搜索到的总数

        //4.2获取文档数组
        SearchHit[] hits = searchHits.getHits();


        List<HotelDoc> hotels = new ArrayList<>();
        for (SearchHit hit : hits) {
            //4.3遍历获取hits数组中每文档里_source属性的值,是个json字符串
            String jsonStr = hit.getSourceAsString();
            //4.4反序列化jsonStr转成实体类对象
            HotelDoc hotelDoc = JSON.parseObject(jsonStr, HotelDoc.class);


            //获取排序值,geo_distance排序的距离
            Object[] sortValues = hit.getSortValues();
            if (sortValues.length != 0) {
                Object sortValue = sortValues[0];
                hotelDoc.setDistance(sortValue);
            }


            hotels.add(hotelDoc);
        }

//        System.err.println(hotels);

        //总条数有了,实体类集合也有了,封装返回
        return new PageResult(total, hotels);
    }

    /**
     * 查询城市、星级、品牌的聚合结果
     *
     * @return 聚合结果，格式：{"城市": ["上海", "北京"], "品牌": ["如家", "希尔顿"]}
     */
    @Override
    public Map<String, List<String>> filters(RequestParams params) {
        try {
            //1.准备SearchRequest
            SearchRequest request = new SearchRequest("hotel");
            //2.准备DSL

            /*先根据条件query*/
            BoolQueryBuilder boolQueryBuilder = getBoolQueryBuilder(params);
            request.source().query(boolQueryBuilder);

            /*再对查询结果聚合*/
            //2.1 设置size
            request.source().size(0);
            //2.2 聚合
            request.source().aggregation(AggregationBuilders.terms("brandAgg").field("brand").size(100));
            request.source().aggregation(AggregationBuilders.terms("cityAgg").field("city").size(100));
            request.source().aggregation(AggregationBuilders.terms("starNameAgg").field("starName").size(100));
            //3. 发出请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //4.解析结果
            Map<String, List<String>> result = new HashMap<>();
            Aggregations aggregations = response.getAggregations();


            List<String> brandList = getStringListByName(aggregations, "brandAgg");
            List<String> cityList = getStringListByName(aggregations, "cityAgg");
            List<String> starNameList = getStringListByName(aggregations, "starNameAgg");

            result.put("brand", brandList);
            result.put("city", cityList);
            result.put("starName", starNameList);

            System.err.println(result);

            return result;

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static List<String> getStringListByName(Aggregations aggregations, String aggName) {
        Terms brandTerms = aggregations.get(aggName);
        List<? extends Terms.Bucket> buckets = brandTerms.getBuckets();
        List<String> brandList = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            String keyAsString = bucket.getKeyAsString();
            brandList.add(keyAsString);
        }
        return brandList;
    }
}
